package com.zrb.matching;

import org.apache.http.Header;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.zrb.discover.Discover_pubishmoneyActivity;
import com.zrb.discover.Discover_publishprojectActivity;
import com.zrb.mobile.BaseActivity;
import com.zrb.mobile.MainTabActivity;
import com.zrb.mobile.MoneyDetailActivity;
import com.zrb.mobile.ProjectDetailActivity;
import com.zrb.mobile.R;
 
import com.zrb.mobile.adapter.FindMoneyAdapter;
import com.zrb.mobile.adapter.MatchingBaseAdapter;
import com.zrb.mobile.adapter.Projectlist_showAdapter;
import com.zrb.mobile.adapter.model.FindMoneyDto;
import com.zrb.mobile.adapter.model.FindProjectDto;
import com.zrb.mobile.pulltorefresh.PullToRefreshBase;
import com.zrb.mobile.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.zrb.mobile.register.User_phone_login;
import com.zrb.mobile.ui.PullToRefreshListViewEx;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.Constants;
import com.zrb.mobile.utility.ZrbRestClient;
import com.zrb.mobile.utility.ZrbRestClient.HttpResponseListener;

public class MatchingActivity extends BaseActivity implements OnClickListener {
	
	
	public static final int PublishProject=Constants.DiscoverProjectIntent;
	public static final int PublishFund=Constants.DiscoverMoneyIntent;
	public static final int MatchProject=Constants.MatchingProject; 
	public static final int MatchFund=Constants.MatchingFund; 
	
	PullToRefreshListViewEx msearchResults;
	//Projectlist_showAdapter mprojectAdapter;
	MatchingBaseAdapter mMatchingAdapter;
	int currentPage;
	Handler mhandler = new Handler();
	View noresultHite;
	View resultLayout;
	Drawable successHite;
	
	
	int curActionId=-1;
	int curId=-1;
	 
	public static void launch(Activity mActivity,int actionType,int curkey){
		
		 if(mActivity==null) return;
		 Intent intent = new Intent(mActivity, MatchingActivity.class);
		 intent.putExtra("actiontype",actionType);
		 intent.putExtra("curId",curkey);
		 mActivity.startActivity(intent);
	}
 	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.project_matching);
		
	    curActionId=this.getIntent().getIntExtra("actiontype", PublishProject);
	    curId=this.getIntent().getIntExtra("curId", curId);
	    initView();
 	  
	    mhandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				msearchResults.setRefreshing(true);
			}
		}, 200);
 	}
	
	private void showMatch(){
 	    this.findViewById(R.id.publish_success_layout).setVisibility(View.GONE);
	    this.findViewById(R.id.match_publish_layout).setVisibility(View.VISIBLE);
	    
	    TextView txtpublishbtn = (TextView)this.findViewById(R.id.match_publish_txtbtn);
	    txtpublishbtn.setText(String.format(MatchingActivity.this.getString(R.string.continue_public_text), curActionId==MatchProject? "资金":"项目"));
	    txtpublishbtn.setOnClickListener(this);
	    
	    TextView txtmatchTitle = (TextView)this.findViewById(R.id.matching_title);
	    txtmatchTitle.setText(R.string.project_matching_publishok1);
	    txtmatchTitle.setCompoundDrawablesWithIntrinsicBounds(  null, null, null, null);
	    
	    TextView txtmatchTitlehite = (TextView)this.findViewById(R.id.matching_titlehite);
	    txtmatchTitlehite.setText(R.string.project_matching_publishok1_hite);
	}
	
	private void initView(){
 	 
		View lefticon = this.findViewById(R.id.title_left_root);
		lefticon.setOnClickListener(this);
		TextView txtTitle = (TextView) this.findViewById(R.id.txt_title);
		boolean isPublishSuccess=(curActionId==PublishProject||curActionId==PublishFund);
		
	    txtTitle.setText(isPublishSuccess ? "发布成功":"为您推荐");
	 
	    ImageView tmphite=   (ImageView)this.findViewById(R.id.success_hite_img);
	    switch(curActionId){
 	      case MatchProject:
	    	  tmphite.setImageResource(R.drawable.icon_tj_xm);
	    	break;
	      case MatchFund:
	    	  tmphite.setImageResource(R.drawable.icon_tj_zj);
	    	break;
	      default:
	    	  tmphite.setImageResource(R.drawable.success_bj);
	    	break;
 	    }
	  
	    if(!isPublishSuccess) showMatch();
	    else{
	    	
	    	this.findViewById(R.id.tv_discover_btn).setOnClickListener(this);
	    	TextView txtpublishbtn = (TextView)this.findViewById(R.id.tv_publish_btn);
	  	    txtpublishbtn.setText(String.format(this.getString(R.string.continue_public_text), curActionId==PublishFund? "资金":"项目"));
	  	    txtpublishbtn.setOnClickListener(this);
	    	
	    }
	    
		noresultHite= this.findViewById(R.id.noresult_hite);
		resultLayout= this.findViewById(R.id.result_layout);
		msearchResults = (PullToRefreshListViewEx) this.findViewById(R.id.discover_list_view);
		msearchResults.setPagesize(100);
		// Set a listener to be invoked when the list should be refreshed.
		msearchResults.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {

				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel( CommonUtil.getcurTime(MatchingActivity.this));
				currentPage = 1;
				mhandler.postDelayed(new Runnable() {
					@Override
					public void run() {
						LoadData(curActionId, curId);
						
						//LoadData("2012-10-10 10:11:11", true); 
					}
				}, 1000);
			}
		});

		
		   if(curActionId==MatchProject||curActionId==PublishFund)
			   mMatchingAdapter = new Projectlist_showAdapter(MatchingActivity.this);
		   else
			   mMatchingAdapter = new FindMoneyAdapter(MatchingActivity.this);
			msearchResults.initAdapter(mMatchingAdapter);
 			msearchResults.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
					// TODO Auto-generated method stub
					
					if(curActionId==MatchProject||curActionId==PublishFund){
				 	  FindProjectDto tmpDto =(FindProjectDto)mMatchingAdapter.getItem(arg2 - 1);
					  Intent intent = new Intent(MatchingActivity.this, ProjectDetailActivity.class);
					  intent.putExtra("id", tmpDto.id);
					  intent.putExtra("title", tmpDto.projectName);
					  startActivity(intent); 
					}
					else{
						
				 		FindMoneyDto tmpDto = (FindMoneyDto)mMatchingAdapter.getItem(arg2 - 1);
						Intent intent = new Intent(MatchingActivity.this, MoneyDetailActivity.class);
						intent.putExtra("id", tmpDto.id);
						intent.putExtra("title", tmpDto.title);
						intent.putExtra("position", arg2 - 1);
						intent.putExtra("from", "1");
	  					startActivity(intent); 
					}
				}
			});
	 
	 
 	}
	
	
	/*		resourceMacthApi/matchlist?type=103&bizid=33013*/
	ZrbRestClient mZrbRestClient;
	private void LoadData(int type, int keyid) {
		String url = String.format("resourceMacthApi/matchlist?type=%1$s&bizid=%2$s", type, keyid);// &tradeDates=%2$s
 	 	
		CommonUtil.InfoLog("resourceMacthApi/list", url);
 		if(mZrbRestClient==null){
			mZrbRestClient=new ZrbRestClient(MatchingActivity.this);
			mZrbRestClient.setOnhttpResponseListener( new HttpResponseListener() {
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,Throwable arg3) {
				CommonUtil.showToast(arg0, MatchingActivity.this);
				if (currentPage > 1) msearchResults.hideloading();
				else
					msearchResults.onRefreshComplete();
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				// loadingview.Hide();
				String results = new String(arg2);
				if (currentPage == 1) 	msearchResults.onRefreshComplete();
				else msearchResults.hideloading();
				try {
 					JSONObject jsonObject2;
					jsonObject2 = new JSONObject(results);
					int retCode= jsonObject2.getInt("res");
 				    if(retCode==1){
 				     
 				    	mMatchingAdapter.setJsonDatas(results, true);
 				    	if(mMatchingAdapter.getCount()>0){
 				    		
 				    		mMatchingAdapter.notifyDataSetChanged();
 				    	    resultLayout.setBackgroundColor(Color.WHITE);
								  
							View footView=  LayoutInflater.from(MatchingActivity.this).inflate(R.layout.project_matching_footer, null);;
							footView.setOnClickListener(MatchingActivity.this);
						    msearchResults.getRefreshableView().addFooterView(footView);
							msearchResults.setPullToRefreshEnabled(false);
 				    	}else {
  							noresultHite.setVisibility(View.VISIBLE);
  							resultLayout.setVisibility(View.GONE);
  						}
				    }
				    else{
 				    	CommonUtil.showToast(jsonObject2.getString("msg"),MatchingActivity.this);
				    }
 			
				} catch (Exception e) {
  					CommonUtil.showToast(R.string.error_serverdata_loadfail, MatchingActivity.this);
				}
			}
		   });
		}
		mZrbRestClient.sessionGet(url );
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {

		case R.id.title_left_root:
			this.finish();
			break;
		case R.id.tv_publish_btn:
			 Intent it4 = new Intent(MatchingActivity.this,curActionId==PublishProject?  Discover_publishprojectActivity.class :Discover_pubishmoneyActivity.class);
			 it4.putExtra("showtab", -1);
			 it4.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
             startActivity(it4);
			 this.finish();
 			 break;
		case R.id.tv_discover_btn:
			 Intent it3 = new Intent(MatchingActivity.this,  MainTabActivity.class );
			 it3.putExtra("showtab", -1);
			 it3.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
             startActivity(it3);
			 this.finish();
			break;
		case R.id.match_publish_txtbtn:
			 Intent it = new Intent(MatchingActivity.this, curActionId==MatchProject
			                                                           ?Discover_pubishmoneyActivity.class
			                                                           :Discover_publishprojectActivity.class);
 			 startActivity(it);
			 MatchingActivity.this.finish(); 
 			break;
		case R.id.match_footer_layout:
			 Intent it2 = new Intent(MatchingActivity.this,  MainTabActivity.class );
			 it2.putExtra("showtab", curActionId==MatchProject? 1:2);
			 it2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
             startActivity(it2);
			 this.finish();
			break;
 			
		}
	}
}
